#ifndef __TCP_SERVER_HPP__
#define __TCP_SERVER_HPP__

#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <functional>
#include "Sock.hpp"
#include "Log.hpp"

using func_t=std::function<void(int)>;

class TcpServer
{
public:
    TcpServer(const uint16_t& port,const std::string& ip="0.0.0.0")
        :_listenfd(-1)
        ,_port(port)
        ,_ip(ip)
    {
        bool res=_sock.CreateServer(_port,_ip);
        if(!res)
        {
            LogMessage(FATAL,"server create error!!!\n");
            return;
        }
        _listenfd=_sock.Fd();
        LogMessage(NORMAL,"server create success!!!\n");
    }

    void Route(int sockfd,uint16_t port,const std::string& ip)
    {
        LogMessage(NORMAL,"get new a link,sockfd:%d port:%d ip:%s\n",sockfd,port,ip.c_str());
        _func(sockfd);
    }

    void Start(const func_t& func)
    {
        _func=func;
        while(true)
        {
            uint16_t port=0;
            std::string ip;
            int sockfd=_sock.Accept(&port,&ip);
            if(sockfd<0) continue;
            std::thread t(&TcpServer::Route,this,sockfd,port,ip);
            t.detach();
        }
    }

private:
    int _listenfd;
    uint16_t _port;
    std::string _ip;
    Sock _sock;
    func_t _func;
};

#endif